package com.hanry;

import java.io.IOException;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.graphics.Color;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.Window;
import android.view.WindowManager;
import android.widget.TextView;

import com.beardedhen.androidbootstrap.FontAwesomeText;
import com.hanry.command.CategoryBit;
import com.hanry.command.Command;
import com.hanry.command.CommandBit;
import com.hanry.command.ValueBit;
import com.hanry.communication.CommunicationConfig;
import com.hanry.communication.CommunicationHandle;
import com.hanry.communication.CommunicationManager;
import com.hanry.component.DirectionSensorEventListener;
import com.hanry.component.FrontAndBackJoystickView;
import com.hanry.component.GravityButtonClickListener;
import com.hanry.component.LeftAndRightJoystickView;
import com.hanry.constant.SmartCarConstant;
import com.hanry.listener.FrontAndBackListener;
import com.hanry.listener.LeftAndRightListener;

@SuppressLint("HandlerLeak")
public class Main extends Activity implements CommandSender{
	protected static final String TAG = "MainActivity";

	
	private FontAwesomeText enableGravityButton;
	private FontAwesomeText TakePicture;
	private FontAwesomeText videoSwitch;
	private FontAwesomeText buttonBack;
	private FontAwesomeText buttonLen;
	public TextView notifyText;
	private FrontAndBackJoystickView frontAndBackJoystick;
	private LeftAndRightJoystickView leftAndRightJoystick;

	private boolean isLightOn = false;
	private boolean enableGravity = false;
	private boolean haveReceivedHeartBreak = false;
	private int recvHeartBreakCounter = 0;
	private int lastrecvHeartBreakCounter = 0;
	private Context appContext;
	private Thread recvMsgThread = null;
	private boolean isEnableRecvMsgThread = false;
	private CommunicationHandle communicationHandle;
	private MjpegView backgroundView = null;
	public DirectionSensorEventListener directionSensorEventListener = null;
	public int lastFrontAndBackCommand = FrontAndBackJoystickView.ORIGIN;
	public int lastLeftAndRightCommand = LeftAndRightJoystickView.ORIGIN;
	public Command lastCommand = null;
	private FontAwesomeText cameraResetButton;
	public ValueBit directionValueBit = new ValueBit(ValueBit.ZERO);
	// 连接类型
	private int connectType;
	// 参数
	private CommunicationConfig config = new CommunicationConfig();
	Handler viewHandler = new Handler() {
		public void handleMessage(Message msg) {
			Log.i("Main", "handle internal Message, id=" + msg.what);

			switch (msg.what) {
			case SmartCarConstant.SEND_COMMAND_ERROR:
				notifyText.setText("命令发送失败");
				break;
			case SmartCarConstant.SEND_COMMAND_SUCCESS:
				notifyText.setText("");
				break;
			default:
				break;
			}
			super.handleMessage(msg);
		}
	};

	private OnClickListener buttonLenClickListener = new OnClickListener() {
		public void onClick(View arg0) {
			if (isLightOn) {
				isLightOn = false;
				sendCommand(new Command(new CategoryBit(CategoryBit.LIGHT),
						new CommandBit(CommandBit.LIGHT0), new ValueBit(ValueBit.ZERO)));
				buttonLen.setTextColor(Color.BLACK);
			} else {
				isLightOn = true;
				sendCommand(new Command(new CategoryBit(CategoryBit.LIGHT),
						new CommandBit(CommandBit.LIGHT0),
						new ValueBit(ValueBit.ONE)));
				buttonLen.setTextColor(Color.YELLOW);
			}

		}
	};
	
	private OnClickListener cameraResetButtonClickListener = new OnClickListener() {
		public void onClick(View arg0) {
			backgroundView.doCameraReset();
		}
	};

	private OnClickListener buttonTakePicClickListener = new OnClickListener() {
		public void onClick(View arg0) {
			if (null != backgroundView) {
				backgroundView.saveBitmap();
			}
		}
	};
	
	private OnClickListener buttonVideoSwitchClickListener = new OnClickListener() {
		public void onClick(View arg0) {
			if(backgroundView.getRunStatus()){
				backgroundView.stopPlayback();
			}else{
				backgroundView.resumePlayback();
			}
		}
	};

	private OnClickListener buttonBackClickListener = new OnClickListener() {
		public void onClick(View arg0) {
			Intent setIntent = new Intent();
			setIntent.setClass(appContext, ModeSelectActivity.class);
			startActivity(setIntent);
		}
	};
	
	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		appContext = this;
		Intent intent = getIntent();
		String stringExtra = intent.getStringExtra(ModeSelectActivity.MODE_TYPE);
		connectType = Integer.valueOf(stringExtra);
        
		this.requestWindowFeature(Window.FEATURE_NO_TITLE);// 隐去标题（应用的名字必须要写在setContentView之前,否则会有异常）
		this.getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
				WindowManager.LayoutParams.FLAG_FULLSCREEN);
		setContentView(R.layout.main);
		// 初始化设置
		initSettings();
		// 初始化公共组件
		initView();
	}
	
	@Override
	public void onPause() {
		super.onPause();
	}

	@Override
	public void onStop() {
		backgroundView.stopPlayback();
		if (enableGravity) {
			this.directionSensorEventListener.unregisterListener();
		}
		try {
			this.communicationHandle.close();
		} catch (IOException e) {
			System.out.println("communicationHandle 关闭失败");
			e.printStackTrace();
		}
		super.onStop();
	}

	@Override
	protected void onResume() {
		super.onResume();
		String cameraUrl = null;
		cameraUrl = SmartCarConstant.CAMERA_VIDEO_URL;
		if (null != cameraUrl && cameraUrl.length() > 4 && connectType == CommunicationManager.WIFI_CONNECT) {
			backgroundView.setSource(cameraUrl);
		}else{
			backgroundView.setSource("");
		}
		backgroundView.resumePlayback();
		if (enableGravity) {
			this.directionSensorEventListener.registerListener();
		}
		// 初始化特有组件
		connectToSmartCar();
	}

	private void connectToSmartCar() {
		if(connectType == CommunicationManager.WIFI_CONNECT){
			initWifiView();
		}else{
			initBluetoohtView();
		}
		// 获取通信句柄
		communicationHandle = CommunicationManager.getCommunication(connectType);
		config.setIpAddr(SmartCarConstant.ROUTER_CONTROL_URL);
		config.setPort(SmartCarConstant.ROUTER_CONTROL_PORT);
		try {
			boolean isPrepared = communicationHandle.prepare(config, this);
			if(isPrepared){
				communicationHandle.open();
			}
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}

	private void initView() {

		buttonBack = (FontAwesomeText) findViewById(R.id.buttonBack);
		buttonBack.setOnClickListener(buttonBackClickListener);

		buttonLen = (FontAwesomeText) findViewById(R.id.btnLen);
		buttonLen.setOnClickListener(buttonLenClickListener);
		buttonLen.setLongClickable(true);

		videoSwitch = (FontAwesomeText) findViewById(R.id.ButtonVideoSwitch);
		TakePicture = (FontAwesomeText) findViewById(R.id.ButtonTakePic);
		TakePicture.setOnClickListener(buttonTakePicClickListener);
		videoSwitch.setOnClickListener(buttonVideoSwitchClickListener);
		cameraResetButton = (FontAwesomeText) findViewById(R.id.ButtonCameraReset);
		cameraResetButton.setOnClickListener(cameraResetButtonClickListener);
		
		enableGravityButton = (FontAwesomeText) findViewById(R.id.ButtonGravity);
		enableGravityButton.setOnClickListener(new GravityButtonClickListener(
				this));
		backgroundView = (MjpegView) findViewById(R.id.mySurfaceView1);
		backgroundView.setCommandSender(this);
		frontAndBackJoystick = (FrontAndBackJoystickView) findViewById(R.id.frontAndBackJoystickView);
		leftAndRightJoystick = (LeftAndRightJoystickView) findViewById(R.id.leftAndRightJoystickView);
		frontAndBackJoystick.setOnFrontAndBackJoystickMoveListener(new FrontAndBackListener(this));
		leftAndRightJoystick.setOnLeftAndRightJoystickMoveListener(new LeftAndRightListener(this));
		notifyText = (TextView) findViewById(R.id.logTextView);
		if (null != notifyText) {
			notifyText.setBackgroundColor(Color.argb(0, 0, 0, 0));// 0~255透明度值
			notifyText.setTextColor(Color.argb(90, 0, 0, 0));
		}
		directionSensorEventListener = new DirectionSensorEventListener(this);
	}

	private void initBluetoohtView() {
		this.videoSwitch.setVisibility(View.GONE);
		this.TakePicture.setVisibility(View.GONE);
		this.TakePicture.setEnabled(false);
	}



	private void initWifiView() {
		this.enableGravityButton.setVisibility(View.VISIBLE);
		this.cameraResetButton.setVisibility(View.VISIBLE);
		this.videoSwitch.setVisibility(View.VISIBLE);
		this.TakePicture.setVisibility(View.VISIBLE);
	}

	void initSettings() {
		SharedPreferences sharedPreferences = getSharedPreferences(SettingsActivity.CONFIG_FILE_NAME, Activity.MODE_PRIVATE); 
		SmartCarConstant.ROUTER_CONTROL_URL = sharedPreferences.getString(SettingsActivity.IP_ADDR_KEY, SettingsActivity.IP_ADDR_DEFAULT);
		SmartCarConstant.CAMERA_VIDEO_URL = sharedPreferences.getString(SettingsActivity.VIDEO_IP_ADDR_KEY, SettingsActivity.VIDEO_IP_ADDR_DEFAULT);
		SmartCarConstant.ROUTER_CONTROL_PORT = Integer.parseInt(sharedPreferences.getString(SettingsActivity.NET_PORT_KEY, SettingsActivity.NET_PORT_DEFAULT));
//		SmartCarConstant.WIFI_SSID_PERFIX = sharedPreferences.getString(SettingsActivity.WIFI_SSID_KEY, SettingsActivity.WIFI_SSID_DEFAULT);

		if (SmartCarConstant.CAMERA_VIDEO_URL != null && !"".equals(SmartCarConstant.CAMERA_VIDEO_URL)) {
			SmartCarConstant.CAMERA_VIDEO_URL = SmartCarConstant.CAMERA_VIDEO_URL_PREFIX + SmartCarConstant.CAMERA_VIDEO_URL
					+ SmartCarConstant.CAMERA_VIDEO_URL_SUFFIX;
		}
	}

	public void sendCommand(Command cmd) {
		Message msg = new Message();
		try {
			communicationHandle.sendMsg(cmd.getBytes());
			msg.what = SmartCarConstant.SEND_COMMAND_SUCCESS;
			viewHandler.sendMessage(msg );
		} catch (Exception e) {
			msg.what = SmartCarConstant.SEND_COMMAND_ERROR;
			viewHandler.sendMessage(msg );
			e.printStackTrace();
		}
		System.out.println("send cmd:"+cmd);
	}
	public void toHideComponent() {
		this.frontAndBackJoystick.setVisibility(View.GONE);
		this.leftAndRightJoystick.setVisibility(View.GONE);
	}

	public void toShowComponent() {
		this.frontAndBackJoystick.setVisibility(View.VISIBLE);
		this.leftAndRightJoystick.setVisibility(View.VISIBLE);
	}
	public boolean getEnableGravity() {
		return enableGravity;
	}

	public void setEnableGravity(boolean enableGravity) {
		this.enableGravity = enableGravity;
	}

	public FontAwesomeText getEnableGravityButton() {
		return enableGravityButton;
	}

	public void setEnableGravityButton(FontAwesomeText enableGravityButton) {
		this.enableGravityButton = enableGravityButton;
	}
}
